<template>
  <div class="goods-container">
    <div class="goods-headbox">
      <!-- 头部搜索 -->
      <div class="goods-head">
        <van-nav-bar :title="$t('m.menu.menu')">
          <template #left>
            <van-icon name="search" size="24" color="black" />
          </template>
        </van-nav-bar>
      </div>
      <!-- 当前商家信息 -->
      <div class="shops-info">
        <van-card :desc="initShopsInfo.slogan" :title="initShopsInfo.name" :thumb="initShopsInfo.img">
          <template #tags>
            <van-tag type="warning" v-if="initShopsInfo.config.has_delivery"> {{ $t('m.home.service_1') }}</van-tag>
            <van-tag type="success" v-if="initShopsInfo.config.has_pickup"> {{ $t('m.home.service_2') }}</van-tag>
            <span class="times">{{ $t('m.goods.time') }}: {{ initShopsInfo.data }}</span>
            <span class="address">{{ $t('m.goods.address') }}: {{ initShopConfig.company_country }} {{ initShopConfig.company_address }}</span>
          </template>
        </van-card>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="gooslist-box">
      <!-- 菜单模块 -->
      <div class="menu-module">
        <div class="goodsmenu">
          <van-sidebar v-model="activeKey">
            <van-sidebar-item :title="item.type" v-for="(item, i) in initGoodsList" :key="i" @click="getMenuID(i)" />
          </van-sidebar>
        </div>
      </div>
      <!-- 商品详情模块 -->
      <div class="goods-module">
        <div class="list-head">{{ initGoodsList[menuID].type }}</div>
        <div class="goodslist">
          <div to="#" v-for="item in initGoodsList[menuID].goodsinfo" :key="item.id" v-show="showGoods">
            <div class="goods-box">
              <van-card
                :price="item.discount_amount > 0 ? item.price - item.discount_amount + '.00' : item.price + '.00'"
                :tag="item.discount_amount > 0 ? '折扣' : ''"
                :desc="'库存: ' + item.stock"
                :title="item.name"
                :thumb="item.image_thumbnail_cdn === '' || item.image_thumbnail_cdn === null ? localIMG : item.image_thumbnail_cdn"
                :currency="$t('m.goods.money')"
                @click="goGoodsInfo(item)"
                :style="{ opacity: item.stock <= 0 ? '0.6' : '' }"
              >
                <template #tags>
                  <span class="discount-amount" v-if="item.discount_amount > 0">￥{{ item.price }}</span>
                </template>
                <template #footer>
                  <div class="countBtn">
                    <van-button class="subBTN" size="mini" @click.stop="subShoppingCart(item.id)" v-if="item.amount > 0">
                      <van-icon name="minus" />
                    </van-button>
                    <span class="amount" v-if="item.amount > 0">{{ item.amount }}</span>
                    <van-button class="addBTN" size="mini" @click.stop="addShoppingCart(item, item.id)" :disabled="item.stock > 0 ? false : true">
                      <van-icon name="plus" />
                    </van-button>
                  </div>
                </template>
              </van-card>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品详情页 -->
    <GoodsInfo @goodsDetails="detailsPageStatus" @addGoodsAmount="getAddNowGoodsItem" @subGoodsAmount="getSubNowGoodsID" v-if="detailsStatus" :nowGoodsItem="nowGoodsItem" :nowOrderList="shoppingCart"></GoodsInfo>
    <!-- 购物车页 -->
    <ShoppingCart :style="{ display: detailsStatus ? 'block' : shoppingCart.length > 0 ? 'block' : 'none' }" :nowOrderList="shoppingCart" :detailsStatus="detailsStatus" :shopConfig="initShopConfig" :shopsInfo="initShopsInfo"> </ShoppingCart>
  </div>
</template>

<script>
import ShoppingCart from '../../../components/GoodsInside/ShoppingCart.vue'
import GoodsInfo from '../../../components/GoodsInside/GoodsInfo.vue'
import bus from '@/eventBus.js'

export default {
  props: ['id'],
  components: {
    ShoppingCart,
    GoodsInfo
  },
  data() {
    return {
      // tabbar 底部标签默认选择 id
      active: 1,
      activeKey: 0,
      menuID: 0,
      nowGoodsItem: {},
      initGoodsList: [],
      initShopsInfo: {},
      initShopConfig: {},
      shoppingCart: [],
      // 判断是否请求到数据，决定是否显示列表
      showGoods: false,
      // 控制商品详情页显示
      detailsStatus: false,
      localIMG: './../static/img/mxbc/Ice_Cream/Ferris_Crispy.jpeg'
    }
  },
  // 初始化请求商店信息、商品列表数据、购物车列表数据
  created() {
    // 初始化当前商品列表 和 店铺属性
    var goodsList = JSON.parse(sessionStorage.getItem('saveGoodsList'))
    // 初始化当前商店信息
    var shopInfo = JSON.parse(sessionStorage.getItem('saveNowShop'))
    // 初始化购物车数据
    var shoppingList = JSON.parse(sessionStorage.getItem(this.id))

    // 判定商店 id 与列表是否一致
    if (Number(this.id) === Number(goodsList.shop_id)) {
      // 若一致，则显示列表
      this.showGoods = true
      // 渲染当前菜单列表
      this.initShopsInfo = shopInfo
      // 渲染当前商品列表
      this.initGoodsList = goodsList.goods_list
      // 初始化当前店铺属性
      this.initShopConfig = goodsList.shop_config
      // 判断是否有购物车数据
      if (shoppingList !== null) {
        this.shoppingCart = shoppingList
      }
    } else {
      this.$toast.fail('数据加载错误')
    }

    // 获取当前城市定位
    setTimeout(() => {
      this.$store.dispatch('getNowPosition')
    }, 500)
    // 提示当前地址不匹配
    setTimeout(() => {
      var changeCity = this.$store.state.changePosition.detailInfo.cityname
      var cityInfo = this.$store.state.nowPositong.detailInfo
      var AddMode = this.$store.state.positionMode
      if (cityInfo.city) {
        var nowCity = cityInfo.city
      } else {
        nowCity = cityInfo.province
      }
      if (changeCity !== undefined && AddMode === true) {
        if (nowCity !== changeCity) {
          this.$toast({
            message: '当前地址不在配送范围内',
            position: 'top',
            duration: 3000
          })
        }
      }
    }, 900)
  },
  // 深度监听购物车订单中数值变化（备注：子组件修改‘父传子的数据’,父组件也会同时变化，通过回传数据实现数据统一）
  watch: {
    shoppingCart: {
      handler(newVal) {
        sessionStorage.setItem(this.id, JSON.stringify(this.shoppingCart))
        for (let i = 0; i < this.initGoodsList.length; i++) {
          for (let k = 0; k < this.initGoodsList[i].goodsinfo.length; k++) {
            var gID = this.initGoodsList[i].goodsinfo[k].id
            this.shoppingCart.find((o, j) => {
              if (gID === o.id) {
                this.initGoodsList[i].goodsinfo[k].amount = o.amount
              }
            })
          }
        }
        // 当购物车一键清空时, 直接初始化
        if (newVal.length === 0) {
          // 初始化当前商品列表
          var goodsList = JSON.parse(sessionStorage.getItem('saveGoodsList'))
          this.initGoodsList = goodsList.goods_list
        }
      },
      deep: true
    }
  },
  methods: {
    // 切换当前点击菜单下的商品数据
    getMenuID(id) {
      this.menuID = id
    },
    // GoodsInfo=> 子传父 传输当前商品添加数据
    getAddNowGoodsItem(val) {
      this.addShoppingCart(val[0], val[1])
    },
    // 同上
    getSubNowGoodsID(val) {
      this.subShoppingCart(val)
    },
    // 商品添加购物车逻辑
    addShoppingCart(item, mid) {
      var cartID = JSON.parse(sessionStorage.getItem(this.id))
      if (cartID === null) {
        this.add(item, mid)
      } else if (this.shoppingCart === []) {
        this.shoppingCart = cartID
        this.add(item, mid)
      } else {
        this.add(item, mid)
      }
    },
    add(item, mid) {
      // 查找判断是否已有商品id
      var findCart = this.shoppingCart.find(o => o.id === mid)
      if (findCart === undefined) {
        item.amount = 1
        this.shoppingCart.push(item)
      } else {
        // 若已有当前商品id, 则只需当前商品数量 +1 即可
        this.shoppingCart.find((o, i) => {
          if (o.id === mid) {
            if (this.shoppingCart[i].amount < 10) {
              this.shoppingCart[i].amount++
            }
            return true
          }
        })
      }
      // 存储购物车列表, 并赋予当前商店id属性值
      sessionStorage.setItem(this.id, JSON.stringify(this.shoppingCart))
    },
    // 购物车减少商品逻辑
    subShoppingCart(mid) {
      this.shoppingCart.find((o, i) => {
        if (o.id === mid) {
          if (this.shoppingCart[i].amount > 0) {
            this.shoppingCart[i].amount--
          }
          return true
        }
      })
    },
    // 商品详情页 子传父 =>ShoppingCart 传入详情页关闭状态, 控制支付栏为 0 时是否显示
    detailsPageStatus(mode) {
      this.detailsStatus = mode
    },
    // 父传子 =>GoodsInfo 控制商品详情页是否显示,并常开支付栏显示
    goGoodsInfo(item) {
      this.detailsStatus = true
      this.nowGoodsItem = item
      bus.$emit('tabbarStatus', false)
    }
  }
}
</script>

<style lang="less">
.goods-container {
  position: fixed;
  max-width: 640px;
  max-height: 100%;
  width: 100%;
  height: 100%;
  left: 50%;
  transform: translateX(-50%);
}
.goods-headbox {
  position: absolute;
  width: 100%;
  height: 173px;
  background: #ededed;
  z-index: -1;
  .goods-head {
    .van-nav-bar__content {
      background: #ededed;
    }
  }
  .shops-info {
    position: absolute;
    width: 97%;
    left: 50%;
    transform: translateX(-50%);
    .van-card {
      display: flex;
      align-items: center;
      height: 120px;
      background: white;
      border-radius: 9px;
    }
    .van-image__img {
      position: fixed;
      top: 10px;
      left: 20px;
      width: 70px;
      height: 70px;
    }
    .van-card__title {
      position: fixed;
      top: 12px;
      height: 1.5em;
      font-size: 1.5em;
      line-height: 1.5em;
    }
    .van-card__desc {
      position: fixed;
      top: 36px;
    }
    .van-tag--warning {
      position: relative;
      top: 3.9em;
      margin-right: 3px;
    }
    .van-tag--success {
      position: relative;
      top: 3.9em;
    }
    .times {
      position: fixed;
      left: 20px;
      bottom: 18px;
      font-size: 0.9em;
      color: #666666;
    }
    .address {
      position: fixed;
      left: 20px;
      bottom: 3px;
      font-size: 0.9em;
      color: #666666;
    }
  }
}

.gooslist-box {
  position: absolute;
  overflow: hidden;
  width: 97%;
  height: 100%;
  top: 173px;
  left: 50%;
  transform: translateX(-50%);
  border-radius: 9px;
  background: white;
  .menu-module {
    float: left;
    overflow: auto;
    width: 33%;
    height: 100%;
    border-right: 0.06em solid #d9d9d9;
    .goodsmenu {
      margin-bottom: 270px;
      .van-sidebar {
        width: 100%;
        text-align: center;
        .van-sidebar-item {
          background: white;
          font-size: 1em;
        }
        .van-sidebar-item--select::before {
          height: 100%;
          left: 97.5%;
          background: orange;
        }
        .van-sidebar-item--select,
        .van-sidebar-item--select:active {
          background: #f2f3f5;
        }
      }
    }
  }
  .goods-module {
    position: absolute;
    overflow: auto;
    width: 67%;
    height: 100%;
    right: 0;
    .list-head {
      position: fixed;
      width: 100%;
      top: 0;
      background: white;
      height: 42px;
      line-height: 42px;
      text-indent: 9px;
      margin-left: 0.07em;
      box-shadow: -4px 5px 5px -9px black;
      z-index: 1;
    }
    .goodslist {
      margin-top: 42px;
      margin-bottom: 270px;
      .goods-box {
        width: 100%;
        margin-bottom: 6px;
        .van-card {
          display: flex;
          background: white;
          margin-left: 0.09em;
          .van-card__header {
            overflow: hidden;
            text-overflow: ellipsis;
          }
          .van-card__thumb {
            position: relative;
            top: 50%;
            transform: translateY(-50%);
            width: 78px;
            height: 78px;
          }
          .van-card__title {
            position: relative;
            top: 0.3em;
            height: 1.2em;
            font-size: 1.2em;
            line-height: 1.2em;
          }
          .van-card__desc {
            position: relative;
            top: 0.3em;
          }
          .van-card__price {
            color: red;
            .van-card__price-currency {
              font-size: 1.4em;
            }
          }
          .van-card__footer {
            position: absolute;
            right: 0.9em;
            top: 58%;
            transform: translateY(-42%);
            .countBtn {
              display: flex;
              align-items: center;
              .amount {
                font-size: 1em;
                color: #696969;
              }
              .subBTN {
                width: 1.8em;
                height: 1.8em;
                border-radius: 50%;
                margin-right: 6px;
                color: black;
                border: 0.09em solid black;
              }
              .addBTN {
                width: 1.85em;
                height: 1.85em;
                border-radius: 50%;
                margin-left: 6px;
                color: white;
                background: orange;
                border: none;
              }
            }
          }
          .discount-amount {
            position: relative;
            top: 12px;
            margin-left: 0.3em;
            color: #b8b8b8;
            font-size: 1.1em;
            text-decoration: line-through;
          }
        }
      }
    }
  }
}
::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}
</style>
